package com.example.demo.algorithm;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflex {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {

        Class<?> targetClass = Class.forName("com.example.demo.algorithm");
        TargetObject targetObject = (TargetObject) targetClass.newInstance();

        /**
         * 获取所有类中所有定义的方法
         */
        Method[] declaredMethods = targetClass.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod.getName());
        }

        /**
         * 获取指定的方法并调用
         */
        Method publicClass = targetClass.getDeclaredMethod("publicClass", String.class);
        publicClass.invoke(targetObject, "JavaGuide");

        /**
         * 掉用private方法
         */
        Method privateMethod = targetClass.getDeclaredMethod("privateMethod");
        //为了调用private方法我们取消安全检查
        privateMethod.setAccessible(true);
        privateMethod.invoke(targetClass);
    }
}
